package makabakaquestionnaire.zutsoftware.framework.file;

import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.entity.UserFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
public class FileServiceImpl implements FileService {
    @Value("${save_file_path}")
    private String filePath;
    FileMapper fileMapper;
    @Autowired
    public void setFileMapper(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    @Override
    public Result upload(MultipartFile file) {

        if (file.isEmpty()){
            return Result.failed(400,"文件为空");
        }
        String OriginalFileName=file.getOriginalFilename();   //获得文件的原始名称
        //考虑桶文件名称会覆盖文件，所以要加工文件名（时间戳+文件名称）
        //OriginalFileName.substring(OriginalFileName.lastIndexOf(".")+1获得文件后缀
        String fileName=System.currentTimeMillis()+"."+OriginalFileName.substring(OriginalFileName.lastIndexOf(".")+1);
        File dest=new File(filePath+fileName);
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            UserFile userFile=new UserFile();
            userFile.setFilePath(filePath+fileName);
            userFile.setFileName(fileName);
            this.saveFilePath(userFile);
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("上传失败");
        }
        return Result.success(fileName);
    }

    @Override
    public Boolean saveFilePath(UserFile userFile) {
         int n=fileMapper.saveFilePath(userFile);
         if (n==1){
             return true;
         }else {
             return false;
         }
    }
}
